﻿using Kstopa.Cache;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace Kstopa.Sqlsugar.Serivices.System.User
{
    public class SysUserService :ISysUserService
    {
        private readonly ISqlSugarRepository<SysUser> _repository;
        private readonly ISimpleCacheService _simpleCacheService;
        private readonly ISysOrgService _sysOrgService;

        public SysUserService(ISqlSugarRepository<SysUser> repository,
            ISimpleCacheService simpleCacheService,
            ISysOrgService sysOrgService
            ) 
        {
            _repository=repository;
            _simpleCacheService = simpleCacheService;
            _sysOrgService = sysOrgService;
        }

        public  async Task<List<SysUser>> GetListAsync()
        {
            //先从Redis拿
            var list = _simpleCacheService.Get<List<SysUser>>(CacheConst.Cache_SysUser);
            if (list == null)
            {
                //redis没有就去数据库拿
                list = await _repository.GetListAsync();
                if (list.Count > 0)
                {
                    //插入Redis
                    _simpleCacheService.Set(CacheConst.Cache_SysUser, list);
                }
            }
            return list;
        }

        
        public async Task Add(UserAddInput input)
        {
            var sysUser = input.Adapt<SysUser>();//实体转换
            if (await _repository.InsertAsync(sysUser))//插入数据
                await RefreshCache();//刷新缓存
        }


        public async Task Edit(UserEditInput input)
        {
            var sysUser = input.Adapt<SysUser>();//实体转换
            if (await _repository.UpdateAsync(input))//插入数据
                await RefreshCache();//刷新缓存
        }


        public async Task Delete(List<BaseIdInput> input)
        {
            //获取所有ID
            var ids = input.Select(it => it.Id).ToList();
            if (ids.Count > 0)
            {
                await _repository.DeleteByIdAsync(ids);
                await RefreshCache();
            }
        }


        public async Task<SqlSugarPagedList<SysUser>> Page(UserPageInput input)
        {
            var query = await GetQuery(input);//获取查询条件
            var pageInfo = await query.ToPagedListAsync(input.Current, input.Size);//分页
            return pageInfo;
        }

        private async Task RefreshCache()
        {
            _simpleCacheService.Remove(CacheConst.Cache_SysUser);//从redis删除
            await GetListAsync();//刷新缓存
        }

        /// <summary>
        /// 获取Sqlsugar的ISugarQueryable
        /// </summary>  
        /// <param name="input"></param>
        /// <returns></returns>
        private async Task<ISugarQueryable<SysUser>> GetQuery(UserPageInput input)
        {
            var orgIds = await _sysOrgService.GetOrgChildIds(input.OrgId);//获取下级机构
            var query =_repository._Db.Queryable<SysUser>().LeftJoin<SysOrg>((u, o) => u.OrgId == o.Id)
                .LeftJoin<SysPosition>((u, o, p) => u.PositionId == p.Id)
                .WhereIF(input.OrgId > 0, u => orgIds.Contains(u.OrgId))//根据组织
                .WhereIF(input.Expression != null, input.Expression?.ToExpression())//动态查询
                .WhereIF(!string.IsNullOrEmpty(input.UserStatus), u => u.UserStatus == input.UserStatus)//根据状态查询
                .WhereIF(!string.IsNullOrEmpty(input.SearchKey), u => u.Name.Contains(input.SearchKey) || u.Account.Contains(input.SearchKey))//根据关键字查询
                .OrderByIF(!string.IsNullOrEmpty(input.SortField), $"u.{input.SortField} {input.SortOrder}")
                .OrderBy(u => u.Id)//排序
                .Select((u, o, p) => new SysUser
                {
                    Id = u.Id.SelectAll(),
                    OrgName = o.Name,
                    PositionName = p.Name,
                    OrgNames = o.Names
                })
                .Mapper(u =>
                {
                    u.Password = null;//密码清空
                    u.Phone = CryptogramUtil.Sm4Decrypt(u.Phone);//手机号解密
                });
            return query;
        }
    }
}
